from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import Dict, Any

mcp = FastMCP("Nghttp2 MCP Server")

"""
Nghttp2 MCP Server
面向软件：nghttp2

提供的 MCP tools：
1. nghttpx_service_control - 控制 nghttpx 服务的启动、停止、重启等操作
   参数：action (str) - 服务控制动作：start/stop/restart/reload/daemon-reload
   返回：统一的命令执行结果 JSON

2. nghttpx_service_status - 检查 nghttpx 服务的状态
   参数：无
   返回：统一的命令执行结果 JSON

3. nghttpx_daemon_mode - 配置 nghttpx 以守护进程模式运行
   参数：无
   返回：统一的命令执行结果 JSON
"""

@mcp.tool()
def nghttpx_service_control(action: str) -> Dict[str, Any]:
    """
    控制 nghttpx 服务的启动、停止、重启等操作
    
    参数:
        action: 服务控制动作，可选值：start/stop/restart/reload/daemon-reload
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    valid_actions = ["start", "stop", "restart", "reload", "daemon-reload"]
    if action not in valid_actions:
        return {
            "success": False,
            "command": f"systemctl {action} nghttpx.service",
            "exit_code": 1,
            "stdout": "",
            "stderr": f"Invalid action: {action}. Valid actions are: {', '.join(valid_actions)}"
        }
    
    command = ["systemctl", action, "nghttpx.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def nghttpx_service_status() -> Dict[str, Any]:
    """
    检查 nghttpx 服务的状态
    
    参数:
        无
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    command = ["systemctl", "status", "nghttpx.service"]
    result = subprocess.run(command, capture_output=True, text=True)
    
    return {
        "success": result.returncode == 0,
        "command": " ".join(command),
        "exit_code": result.returncode,
        "stdout": result.stdout,
        "stderr": result.stderr
    }

@mcp.tool()
def nghttpx_daemon_mode() -> Dict[str, Any]:
    """
    配置 nghttpx 以守护进程模式运行
    
    参数:
        无
    
    返回:
        JSON 结构:
        {
            "success": bool,      # 命令是否成功执行
            "command": str,       # 执行的完整命令
            "exit_code": int,     # 命令退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    # 修改服务文件以启用守护进程模式
    sed_command = ["sed", "-i", "s|ExecStart=/usr/bin/nghttpx|ExecStart=/usr/bin/nghttpx -D|g", "/usr/lib/systemd/system/nghttpx.service"]
    result1 = subprocess.run(sed_command, capture_output=True, text=True)
    
    if result1.returncode != 0:
        return {
            "success": False,
            "command": " ".join(sed_command),
            "exit_code": result1.returncode,
            "stdout": result1.stdout,
            "stderr": result1.stderr
        }
    
    # 重新加载 systemd 配置
    reload_command = ["systemctl", "daemon-reload"]
    result2 = subprocess.run(reload_command, capture_output=True, text=True)
    
    return {
        "success": result2.returncode == 0,
        "command": f"{' '.join(sed_command)} && {' '.join(reload_command)}",
        "exit_code": result2.returncode,
        "stdout": f"sed output: {result1.stdout}\nsystemctl output: {result2.stdout}",
        "stderr": f"sed error: {result1.stderr}\nsystemctl error: {result2.stderr}"
    }

if __name__ == "__main__":
    mcp.run()